package com.apkplug.osgi.activity;
import java.io.File;
import java.util.List;
import org.apkplug.Bundle.BundleControl;
import org.apkplug.Bundle.installCallback;
import org.apkplug.app.FrameworkFactory;
import org.apkplug.app.FrameworkInstance;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.framework.SynchronousBundleListener;
import com.apkplug.adapter.ListBundleAdapter;
import com.apkplug.osgi.service.printLog;
import com.apkplug.osgi.serviceImp.showViewImp;
import com.apkplug.osgiservice.R;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 0.0.1 版本新增安装本地插件接口
 * MainActivity.install(String path,installCallback callback)
 * @author 梁前武 qq 1587790525
 * www.apkplug.com
 */
public class MainActivity extends Activity {
	private FrameworkInstance frame=null;
	private List<org.osgi.framework.Bundle> bundles=null;
	private TextView info=null;
	private showViewImp	showView=null;
	private ListView bundlelist =null;
	private ListBundleAdapter adapter=null;
	private ViewActivator activator=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		info =(TextView)this.findViewById(R.id.info);
		
		LinearLayout layout=(LinearLayout)this.findViewById(R.id.layout);
		showView=new showViewImp(layout);
		activator=new ViewActivator(showView);
		Button log =(Button)this.findViewById(R.id.log);
		log.setOnClickListener(
				new OnClickListener(){
					@Override
					public void onClick(View arg0) {
						printLog log=activator.getService();
						if(log==null){
							Toast.makeText(MainActivity.this,
									"没有打印服务，请先启动一个插件1试试",
									Toast.LENGTH_LONG).show();
						}else{
							log.log("hello 插件");
						}
					}
				});
		try
        {
        	//启动框架
			//http://www.apkplug.com/javadoc/Maindoc1.4.6/
			//org.apkplug.app 
			//     接口 FrameworkInstance
			//com.apkplug.appServiceManager 为Service.jar包提供的插件托管服务启动BundleActivator
			List<BundleActivator> activators=new java.util.ArrayList<BundleActivator>();
            //将服务加入框架，框架将在启动时启动这些服
			activators.add(activator);
			frame=FrameworkFactory.getInstance().start(activators,MainActivity.this,new MyProperty(this.getApplicationContext()));
			
        }
        catch (Exception ex)
        {
            System.err.println("Could not create : " + ex);
            //ex.printStackTrace();
            int nPid = android.os.Process.myPid();
			android.os.Process.killProcess(nPid);
        }
		
		initBundleList();
		//监听插件安装状态已动态更新列表
		ListenerBundleEvent();
	}
	
	/**
	 * 初始化显示已安装插件的UI
	 */
	public void initBundleList(){
		 //已安装插件列表
        bundlelist=(ListView)findViewById(R.id.bundlelist);
		bundles=new java.util.ArrayList<org.osgi.framework.Bundle>();
		BundleContext context =frame.getSystemBundleContext();
		for(int i=0;i<context.getBundles().length;i++)
		{
			//获取已安装插件
				bundles.add(context.getBundles()[i]);        	        
		}
		adapter=new ListBundleAdapter(MainActivity.this,bundles);
		bundlelist.setAdapter(adapter);
	}
	
	/**
	 * 监听插件安装事件，当有新插件安装或卸载时成功也更新一下
	 */
 	public void ListenerBundleEvent(){
 		frame.getSystemBundleContext()
			.addBundleListener(
					new SynchronousBundleListener(){
	
						public void bundleChanged(BundleEvent event) {
							//把插件列表清空
							bundles.clear();
							BundleContext context =frame.getSystemBundleContext();
							for(int i=0;i<context.getBundles().length;i++)
							{
									bundles.add(context.getBundles()[i]);        	        
	
							}
							adapter.notifyDataSetChanged();
						}
					
			});
	}
	
 	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() != KeyEvent.ACTION_UP) {
			AlertDialog.Builder alertbBuilder = new AlertDialog.Builder(this);
			alertbBuilder
					.setTitle("退出应用")
					.setMessage("你确定要退出程序?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									//MyProperty中调试模式设置为true调用shutdown将清理已安装插件缓存
									//以在下次启动时重新安�?
									frame.shutdown();
									int nPid = android.os.Process.myPid();
									android.os.Process.killProcess(nPid);
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							}).create();
			alertbBuilder.show();
			return true;
		} else {
			return super.dispatchKeyEvent(event);
		}
	} 
}
